﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Server.Common
{
    public class HttpUtil
    {
        public static bool HttpPost(string url, JObject json)
        {
            HttpWebResponse res;
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;

                string httpUrl = ConfigUtil.GetAppSettings("javaService");
                //HttpWebRequest request = WebRequest.Create(new Uri($"{System.Configuration.ConfigurationManager.AppSettings["javaService"]}/{url}")) as HttpWebRequest; //创建请求
                HttpWebRequest request = WebRequest.Create(new Uri($"{httpUrl}/{url}")) as HttpWebRequest; //创建请求
                request.AllowAutoRedirect = true;
                request.Method = "POST"; //请求方式为post
                request.ContentType = "application/json";

                byte[] jsonbyte = Encoding.UTF8.GetBytes(json.ToString());
                Stream postStream = request.GetRequestStream();
                postStream.Write(jsonbyte, 0, jsonbyte.Length);
                postStream.Close();
                //发送请求并获取相应回应数据       
                res = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                string content = sr.ReadToEnd(); //获得响应字符串
                JObject result = JsonConvert.DeserializeObject<JObject>(content);


                return Convert.ToBoolean(result["data"].ToString());
            }
            catch (WebException ex)
            {
                Log4Util.LogInstance.Error(typeof(HttpUtil), $"请求Post地址【{url}】错误", ex);
                throw ex;
            }
        }


        public static T HttpGet<T>(string url)
        {
            try
            {
                string httpUrl = ConfigUtil.GetAppSettings("javaService");
                HttpWebRequest request = WebRequest.Create(new Uri($"{httpUrl}/{url}")) as HttpWebRequest; //创建请求
                request.Method = "GET";
                request.ContentType = "application/json";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream myResponseStream = response.GetResponseStream())
                {
                    using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8))
                    {
                        string retString = myStreamReader.ReadToEnd();
                        JObject result = JsonConvert.DeserializeObject<JObject>(retString);
                        if (result.ContainsKey("code") && result.GetValue("code").ToString() != "0000") throw new Exception(result.ContainsKey("msg") ? result.GetValue("msg").ToString() : "未知错误信息");
                        if (result.ContainsKey("data"))
                        {
                            return JsonConvert.DeserializeObject<T>(result.GetValue("data").ToString());
                        }
                        else
                        {
                            return default(T);
                        }
                    }
                };
                //return null;
            }
            catch (Exception ex)
            {
                Log4Util.LogInstance.Error(typeof(HttpUtil), $"请求Get地址【{url}】错误", ex);
                throw ex;
            }
        }
    }
}
